<template>
  <div class="editor-wrap">
    
    <!-- 富文本编辑 -->
    <quill-editor 
            v-model="content" 
            ref="myQuillEditor" 
            :options="editorOption" 
            @blur="onEditorBlur($event)" 
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)">

        </quill-editor>


        <!-- 图片添加 -->
      <upload-dialog
          :visible.sync="uploadDialogVisible"
          @close="uploadDialogClose"
          @confirm="insertImgToContent"
      ></upload-dialog>


      <!-- 百度api调用抽屉 -->
      <el-drawer
        class="assist-writing"
        title="智能创作"
        :visible.sync="drawer"
        direction="rtl"
        :wrapperClosable="false"
      >
        
        <div class="assist-writing-main">
          
          <!-- 顶部切换区域 -->  
          <div class="radio-tab-wrap">
            <el-radio-group v-model="tabRiado" size="mini">
              <el-radio-button label="热点发现"></el-radio-button>
              <el-radio-button label="文本纠错"></el-radio-button>
              <el-radio-button label="发文助手"></el-radio-button>
            </el-radio-group>
          </div>



          <!-- 内容展示区域 -->
          <div class="result-wrap">
            
            <!-- 提示内容 -->
            <div class="tips">请先添加标题，同时正文不少于200字，再点击自动生成/全部生成</div>

            <div class="handle-list">
              
              <!-- 接口调用操作区 -->
              <div class="api-opearte">
                <div class="opearte-left">
                  <span class="title">文章摘要</span>
                  <span class="sub-title">根据文章内容，自动生成摘要</span>
                </div>
     
                <div class="opearte-right">
                  <el-button type="primary" size="mini" @click="topic">生成</el-button>
                </div>
              </div>

              <!-- 返回结果区域 -->
              <div class="api-result">
                
              </div>

            </div>
          </div>
          

        </div>

      </el-drawer>

  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import Quill from 'quill'


/*创建自定义图片*/
const Embed = Quill.import('blots/block/embed');

class IpcImage extends Embed{
  static create(value){
    let node = super.create();
    IpcImage.buildDiv(value,node)
    return node
  }

  static value(node) {
    return node.dataset.src;
  }

  static buildDiv(value,node){
    node.setAttribute('data-name', 'ipc-image');
    node.setAttribute('data-src', value);
    Object.assign(node.style,{
      textAlign:'center',
      lineHeight:'0',
      margin:'20px 0'
    });
    let image = document.createElement('img');
    image.setAttribute('width',440);
    image.setAttribute('src',value);

    node.appendChild(image)

  }
}


IpcImage.blotName = 'ipcImage';
IpcImage.className = 'ql-ipace-image';
IpcImage.tagName = 'div';

Quill.register(IpcImage)

//定义富文本工具栏标题
const titleConfig = {
    "ql-bold": "加粗" ,
    "ql-color": "颜色",
    "ql-font": "字体",
    "ql-code": "插入代码",
    "ql-italic": "斜体",
    "ql-link": "添加链接",
    "ql-background": "背景颜色",
    "ql-size": "字体大小",
    "ql-strike": "删除线",
    "ql-script": "上标/下标",
    "ql-underline": "下划线",
    "ql-blockquote": "引用",
    "ql-header": "标题",
    "ql-indent": "缩进",
    "ql-list": "列表",
    "ql-align": "文本对齐",
    "ql-direction": "文本方向",
    "ql-code-block": "代码块",
    "ql-formula": "公式",
    "ql-image": "图片",
    "ql-video": "视频",
    "ql-clean": "清除字体样式",
    "ql-upload": "文件",
    "ql-customImage": "上传图片"
};


import UploadDialog from '../uploadDialog';

import website from '@/config/website'

const imgPreviewPrefix = website.imgPreviewPrefix



import {
  ecnet,
  summary,
  keyword,
  topic
} from "@/api/substance/publish"
export default{
  components: {
        quillEditor,
        UploadDialog,
    },
  props:{
    value:{
      type:String,
      default:''
    }
  },
  watch:{
    //监听value的变化，更新本地数据
    value(newVal){
      this.content = newVal;
    },
    //监听本地数据变化，使用input事件通知父组件更新
    content(newVal){
      this.$emit('input',newVal);
    }
  },
  data(){
    var _this = this;

    return{
      //右侧抽屉
      drawer:true,
      tabRiado:'热点发现',
      uploadDialogVisible:false,
      content:this.value,
      editorOption: {
                placeholder: '请输入正文',
                modules:{
                  toolbar:{
                      container:[
                        ['bold','italic','underline','strike'],
                        ['blockquote','code-block'],
                        [{'header':1},{'header':2}],
                        [{'list':'ordered'},{'list':'bullet'}],
                        [{'script':'sub'},{'script':'super'}],
                        [{'indent':'-1'},{'indent':'+1'}],
                        [{'direction':'rtl'}],
                        [{'size':['small',false,'large','huge']}],
                        [{'header':[1,2,3,4,5,6,false]}],
                        [{'color':[]},{'background':[]}],
                        [{'font':[]}],
                        [{'align':[]}],
                        ['clean'],
                        ['customImage']
                      ],
                      handlers:{
                        shadeBox:null,
                        customImage:function(){
                            _this.uploadDialogVisible = true
                        }
                      }

                  }

                }

            },
    }
  },
  mounted(){
    this.addQuillTitle();
    this.initButton();
  },
  computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        },
    },
  methods:{
    summary(){
      var content = "记者从财政部了解到，近日，中央财政提前下达全国28个省2020年中央财政专项扶贫资金预算1136亿元，约占2019年中央财政专项扶贫资金1261亿元的90%。其中，继续重点加大对“三区三州”等深度贫困地区支dd持力度，专门安排“三区三州”144亿元，并将资金分解到具体区、州。同时，财政部督促各地继续深入推进贫困县涉农资金整合试点工作，以强化对脱贫攻坚决战的投入保障。The media could not be loaded, either because the server or network failed odr because the format is not supported.11月21日上午，合肥视涯项目投产仪式在合肥新站高新区举行，视觉标志全球最大的硅基OLED生产工厂正式投产。中共安徽省委常委、合肥市委书记宋国权，合肥市副市长王文松出席投产仪式。是目前全球最大的、唯一专注于12吋晶圆硅基OLED微型显示组件研发生产基地。";
      var title = "测试标题";
      var max_summary_len = 100;
      summary(title,content,max_summary_len).then((res) => {
        console.log("%c百度api摘要","background:#f09;color#fff");
        console.log(res);
      })
    },
    keyword(){
      var content = "记者从财政部了解到，近日，中央财政提前下达全国28个省2020年中央财政专项扶贫资金预算1136亿元，约占2019年中央财政专项扶贫资金1261亿元的90%。其中，继续重点加大对“三区三州”等深度贫困地区支dd持力度，专门安排“三区三州”144亿元，并将资金分解到具体区、州。同时，财政部督促各地继续深入推进贫困县涉农资金整合试点工作，以强化对脱贫攻坚决战的投入保障。The media could not be loaded, either because the server or network failed odr because the format is not supported.11月21日上午，合肥视涯项目投产仪式在合肥新站高新区举行，视觉标志全球最大的硅基OLED生产工厂正式投产。中共安徽省委常委、合肥市委书记宋国权，合肥市副市长王文松出席投产仪式。是目前全球最大的、唯一专注于12吋晶圆硅基OLED微型显示组件研发生产基地。";
      var title = "测试标题";
      keyword(title,content).then((res) => {
        console.log("%c百度api标签","background:#f09;color#fff");
        console.log(res);
      })
    },
    topic(){
      var content = "记者从财政部了解到，近日，中央财政提前下达全国28个省2020年中央财政专项扶贫资金预算1136亿元，约占2019年中央财政专项扶贫资金1261亿元的90%。其中，继续重点加大对“三区三州”等深度贫困地区支dd持力度，专门安排“三区三州”144亿元，并将资金分解到具体区、州。同时，财政部督促各地继续深入推进贫困县涉农资金整合试点工作，以强化对脱贫攻坚决战的投入保障。The media could not be loaded, either because the server or network failed odr because the format is not supported.11月21日上午，合肥视涯项目投产仪式在合肥新站高新区举行，视觉标志全球最大的硅基OLED生产工厂正式投产。中共安徽省委常委、合肥市委书记宋国权，合肥市副市长王文松出席投产仪式。是目前全球最大的、唯一专注于12吋晶圆硅基OLED微型显示组件研发生产基地。";
      var title = "智慧零售";
      topic(title,content).then((res) => {
        console.log("%c百度api文章分类","background:#f09;color#fff");
        console.log(res);
      })
    },
    ecnet(){
      var text = "11月17日晚建，不时有旅客进出黑笼江兵馆。新京报记者 刘名洋 摄";
      ecnet(text).then((res) => {
        console.log("%c百度api纠错","background:#f09;color#fff");
        console.log(res)
        var result = res.data.data;
        //纠错后正确的文本
        var correct = result.item.correct_query;
        var err_arr = result.item.vec_fragment;
      })
    },
    // 失去焦点事件
    onEditorBlur(ev){

    }, 
    // 获得焦点事件
        onEditorFocus(ev){

        },
        // 内容改变事件 
        onEditorChange(ev){

        }, 
        //添加富文本标题提示
        addQuillTitle(){
            const oToolBar = document.querySelector(".ql-toolbar"),
                aButton = oToolBar.querySelectorAll("button"),
                aSelect = oToolBar.querySelectorAll("select");

            aButton.forEach(function(item){
                if(item.className === "ql-script"){
                  item.value === "sub" ? (item.title="下标") : (item.title="上标")
                }else if(item.className === "ql-indent"){
                  item.value === "+1" ? (item.title="向右缩进") : (item.title="向左缩进")
                }else{
                  item.title = titleConfig[item.classList[0]];
                }
            });

            aSelect.forEach(function(item){
                item.parentNode.title = titleConfig[item.classList[0]];
            });
        },
        //初始化自定义按钮
        initButton(){
            //图片上传添加按钮
            const customImage = document.querySelector('.ql-customImage');
            customImage.innerHTML="<i class=\"icon iconfont ipc-add-image\"></i>";
        },
        //选择图片模态框关闭
        uploadDialogClose(){
            this.uploadDialogVisible = false;
        },
        //上传图片成功后点击确定插入图片到富文本
        insertImgToContent(imgs){
            let quill = this.$refs.myQuillEditor.quill;
            for(var i=0;i<imgs.length;i++){
              /*imgs[i]['selected'] = false;
              if(imgs[i]['selectIndex']){
                  delete imgs[i]['selectIndex']
              }*/

              let length = quill.selection.savedRange.index;
              quill.insertEmbed(length !== null ? length : 0,'ipcImage',imgPreviewPrefix+imgs[i],Quill.sources.USER)
            }

            //将插入的图片推入缓存去
            //this.cacheImgs = this.cacheImgs.concat(imgs);
            this.$emit('updateCacheImg',imgs);

            console.log("%c插入到正文的图片","background:#90c;color:#fff")
            console.log(imgs)

            //关闭模态框
            this.uploadDialogVisible = false;
        },
  }

} 

</script>


<style>
  /*设置富文本高度*/
  .ql-editor{
    height:350px;
    line-height: 2;
  }

  .ql-editor.ql-blank::before {
    font-style: normal;
    font-size: 16px;
    line-height: 25px;
    color: #999;
    
  }

  .ql-snow .ql-editor img {
    max-width: 440px;
  }
</style>


<style lang="scss">

.assist-writing-main{
  padding:0 15px;
  
  .radio-tab-wrap{
    text-align: center;
    border-bottom: 1px solid #e8e8e8;
    margin-left: -15px;
    margin-right: -15px;
    padding: 10px 0;
  }
  .result-wrap{
    .tips{
      padding: 10px 0;
      font-size: 12px;
      color: #c00;
    }
    .handle-list{
      border-bottom: 1px solid #e8e8e8;
      .api-opearte{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        .opearte-left{
          display: flex;
          flex-direction: column;
          font-size: 12px;
          .title{
            color: #000;
            margin-bottom: 5px;
          }
          .sub-title{
            color: #999;
          }
        }
      }

    }
  }
  
  
}

</style>
